package webdemo;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
/*
 * a simple static http server
 * @author www.zuidaima.com
 */
public class SimpleHttpServer {
	
	public static void main(String[] args) throws Exception {
		HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
		server.createContext("/getinfo", new MyHandler());
		server.setExecutor(null); // creates a default executor
		server.start();
	}

	static class MyHandler implements HttpHandler {
		SinaLevel2Demo3 demo3 = new SinaLevel2Demo3();
		public void sendMsg(HttpExchange exchange,JSONObject obj){
			OutputStream os = exchange.getResponseBody();
			try {
				exchange.sendResponseHeaders(200, obj.toString().length());
				os.write(obj.toString().getBytes());
				os.flush();
				os.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		public void handle(HttpExchange httpExchange) throws IOException {

			try{
				Map<String, String> paramMap = new HashMap<String, String>();  
			    String query = httpExchange.getRequestURI().getQuery();  
			    System.out.println(query);
		        String [] arrayStr = query.split("&");  
		        for(String str : arrayStr){  
		            paramMap.put(str.split("=")[0], str.split("=")[1]);  
		        }  
		        JSONObject obj = new JSONObject();
		        if(paramMap.get("method").equals("addstock")){
		        	String stockList = paramMap.get("stocklist");
			        demo3.startDemo(2, stockList);
			        obj.put("errorcode", 0);
		        }
		        if(paramMap.get("method").equals("gettodayinfo")){
			        obj.put("errorcode", 0);
			        obj.put("data", demo3.getTodayData(null));
		        }
		        if(paramMap.get("method").equals("stopcollect")){
			        obj.put("errorcode", 0);
			        demo3.stopAstock("600050");
		        }
		        sendMsg(httpExchange,obj);
			}catch(Exception  ex){
				JSONObject obj = new JSONObject();
				obj.put("errorcode", -1);
				ex.printStackTrace();
		        sendMsg(httpExchange,obj);
			}
		}
	}

}